<template>
  <div class="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
    <!-- Element Selector Button -->
    <button
      @click="toggleElementSelector"
      :class="[
        'px-3 py-2 rounded shadow-lg text-sm font-medium transition-all',
        isSelectingElement 
          ? 'bg-orange-500 text-white' 
          : 'bg-blue-500 text-white hover:bg-blue-600'
      ]"
    >
      {{ isSelectingElement ? '选择中...' : '选择控件' }}
    </button>

    <!-- Console Errors Button -->
    <button
      @click="sendConsoleErrors"
      :disabled="consoleErrors.length === 0"
      :class="[
        'px-3 py-2 rounded shadow-lg text-sm font-medium transition-all',
        consoleErrors.length > 0
          ? 'bg-red-500 text-white hover:bg-red-600'
          : 'bg-gray-300 text-gray-500 cursor-not-allowed'
      ]"
    >
      控制台错误 ({{ consoleErrors.length }})
    </button>

    <!-- Selection Overlay -->
    <div
      v-if="isSelectingElement"
      class="fixed inset-0 z-40 cursor-crosshair debug-picker-overlay"
      @mousemove="onMouseMove"
      @click.stop.prevent="onElementClick"
    >
      <div
        v-if="highlightedElement"
        :style="highlightStyle"
        class="absolute border-2 border-blue-500 bg-blue-100 bg-opacity-20 pointer-events-none"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'

const isSelectingElement = ref(false)
const highlightedElement = ref(null)
const consoleErrors = ref([])

// Highlight style for element selection
const highlightStyle = computed(() => {
  if (!highlightedElement.value) return {}
  const rect = highlightedElement.value.getBoundingClientRect()
  return {
    left: `${rect.left + window.scrollX}px`,
    top: `${rect.top + window.scrollY}px`,
    width: `${rect.width}px`,
    height: `${rect.height}px`
  }
})

// Toggle element selector mode
const toggleElementSelector = () => {
  isSelectingElement.value = !isSelectingElement.value
  if (!isSelectingElement.value) {
    highlightedElement.value = null
    document.body.style.cursor = 'default'
  } else {
    document.body.style.cursor = 'crosshair'
  }
}

// Handle mouse move during element selection
const onMouseMove = (event) => {
  if (!isSelectingElement.value) return

  // Temporarily hide the overlay to get the real element underneath
  const overlay = document.querySelector('.debug-picker-overlay')
  if (overlay) {
    overlay.style.pointerEvents = 'none'
  }
  
  const element = document.elementFromPoint(event.clientX, event.clientY)
  highlightedElement.value = element && !element.classList?.contains('debug-tools') ? element : null
  
  // Restore overlay pointer events
  if (overlay) {
    overlay.style.pointerEvents = 'auto'
  }
}

// Handle element click
const onElementClick = (event) => {
  if (!isSelectingElement.value) return

  event.preventDefault()
  event.stopPropagation()

  // Temporarily hide the overlay to get the real element underneath
  const overlay = document.querySelector('.debug-picker-overlay')
  if (overlay) {
    overlay.style.pointerEvents = 'none'
  }

  const element = document.elementFromPoint(event.clientX, event.clientY)
  
  // Restore overlay pointer events
  if (overlay) {
    overlay.style.pointerEvents = 'auto'
  }

  if (element) {
    sendElementToWindsurf(element)
  }

  toggleElementSelector()
}

// Send element information to Windsurf
const sendElementToWindsurf = (element) => {
  const elementInfo = {
    tagName: element.tagName,
    id: element.id || '',
    className: element.className || '',
    textContent: element.textContent?.trim().substring(0, 100) || '',
    attributes: Object.fromEntries(
      Array.from(element.attributes)
        .map(attr => [attr.name, attr.value])
        .filter(([name]) => !['id', 'class'].includes(name))
    ),
    rect: element.getBoundingClientRect(),
    selector: generateSelector(element),
    outerHTML: element.outerHTML.substring(0, 500) + (element.outerHTML.length > 500 ? '...' : '')
  }
  
  const message = `选中的控件信息：
\`\`\`html
${elementInfo.outerHTML}
\`\`\`

**控件详情：**
- 标签：${elementInfo.tagName}
- ID：${elementInfo.id || '无'}
- 类名：${elementInfo.className || '无'}
- 文本内容：${elementInfo.textContent}
- 选择器：${elementInfo.selector}
- 位置：${Math.round(elementInfo.rect.left)}, ${Math.round(elementInfo.rect.top)}
- 尺寸：${Math.round(elementInfo.rect.width)} × ${Math.round(elementInfo.rect.height)}

**属性：**
${Object.entries(elementInfo.attributes).map(([key, value]) => `- ${key}: ${value}`).join('\n') || '无'}`

  copyToClipboard(message)
  console.log('控件信息已复制到剪贴板，可粘贴到 Windsurf 聊天框：', message)
  
  // Show success feedback
  showNotification('控件信息已复制到剪贴板')
}

// Generate CSS selector for element
const generateSelector = (element) => {
  if (element.id) return `#${element.id}`
  
  const path = []
  let current = element
  
  while (current && current !== document.body) {
    let selector = current.tagName.toLowerCase()
    
    if (current.className) {
      const classes = current.className.split(' ').filter(c => c.trim())
      if (classes.length > 0) {
        selector += '.' + classes.join('.')
      }
    }
    
    // Add nth-child if needed for uniqueness
    if (current.parentElement) {
      const siblings = Array.from(current.parentElement.children).filter(
        child => child.tagName === current.tagName
      )
      if (siblings.length > 1) {
        const index = siblings.indexOf(current) + 1
        selector += `:nth-child(${index})`
      }
    }
    
    path.unshift(selector)
    current = current.parentElement
  }
  
  return path.join(' > ')
}

// Send console errors to Windsurf
const sendConsoleErrors = () => {
  if (consoleErrors.value.length === 0) return
  
  const errorsText = consoleErrors.value.map((error, index) => 
    `${index + 1}. [${error.timestamp}] ${error.level.toUpperCase()}: ${error.message}
   位置：${error.url}:${error.line}:${error.column}
   堆栈：${error.stack || '无'}`
  ).join('\n\n')
  
  const message = `控制台错误信息 (共 ${consoleErrors.value.length} 个)：
\`\`\`
${errorsText}
\`\`\``
  
  copyToClipboard(message)
  console.log('控制台错误已复制到剪贴板，可粘贴到 Windsurf 聊天框：', message)
  
  // Clear errors after sending
  consoleErrors.value = []
  showNotification('控制台错误已复制到剪贴板')
}

// Copy text to clipboard
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
  } catch (err) {
    // Fallback for older browsers
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
  }
}

// Show notification
const showNotification = (message) => {
  const notification = document.createElement('div')
  notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg z-50'
  notification.textContent = message
  document.body.appendChild(notification)
  
  setTimeout(() => {
    document.body.removeChild(notification)
  }, 3000)
}

// Console error handling
const originalConsoleError = console.error
const originalConsoleWarn = console.warn

const consoleHandler = (level, ...args) => {
  // Call original console method
  if (level === 'error') {
    originalConsoleError.apply(console, args)
  } else if (level === 'warn') {
    originalConsoleWarn.apply(console, args)
  }
  
  // Store error information
  const message = args.map(arg => 
    typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
  ).join(' ')
  
  // Filter out TinyMCE language loading errors (handled gracefully)
  if (message.includes('Failed to load language: zh_CN') || 
      message.includes('@tinymce/tinymce-i18n') ||
      message.includes('tinymce-i18n') ||
      message.includes('Failed to load plugin: paste') ||
      message.includes('Failed to load plugin: hr')) {
    return // Don't show this error in debug tools
  }
  
  const errorInfo = {
    level,
    message,
    timestamp: new Date().toLocaleTimeString(),
    url: window.location.href,
    line: 0,
    column: 0,
    stack: null
  }
  
  // Try to extract line/column info from error objects
  if (args[0] instanceof Error) {
    const error = args[0]
    errorInfo.stack = error.stack
    const match = error.stack.match(/at.*\((.*?):(\d+):(\d+)\)/)
    if (match) {
      errorInfo.url = match[1]
      errorInfo.line = parseInt(match[2])
      errorInfo.column = parseInt(match[3])
    }
  }
  
  consoleErrors.value.push(errorInfo)
  
  // Keep only last 50 errors
  if (consoleErrors.value.length > 50) {
    consoleErrors.value.shift()
  }
}

// Handle unhandled errors
const unhandledErrorHandler = (event) => {
  consoleHandler('error', event.error || new Error(event.message))
}

const unhandledRejectionHandler = (event) => {
  consoleHandler('error', event.reason || new Error('Unhandled promise rejection'))
}

onMounted(() => {
  // Override console methods
  console.error = (...args) => consoleHandler('error', ...args)
  console.warn = (...args) => consoleHandler('warn', ...args)
  
  // Add global error handlers
  window.addEventListener('error', unhandledErrorHandler)
  window.addEventListener('unhandledrejection', unhandledRejectionHandler)
})

onBeforeUnmount(() => {
  // Restore original console methods
  console.error = originalConsoleError
  console.warn = originalConsoleWarn
  
  // Remove global error handlers
  window.removeEventListener('error', unhandledErrorHandler)
  window.removeEventListener('unhandledrejection', unhandledRejectionHandler)
  
  // Reset cursor
  document.body.style.cursor = 'default'
})
</script>

<style scoped>
/* Additional styles if needed */
.debug-tools {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
</style>
